<template>
    <el-drawer v-model="visible" :title="`${isCreate ? '添加' : '修改'}事件`" :class="$style['modify-drawer']" size="650px"
        :close-on-click-modal="false" :close-on-press-escape="false" @close="onCancel">
        <el-form ref="refForm" :model="formModel" label-width="auto" :rules="rules" :class="$style['modify-wrapper']">
            <el-form-item label="调用模块" prop="module_id">
                <el-select v-model="formModel.module_id" placeholder="调用模块" clearable>
                    <el-option :key="index" v-for="(item, index) in modules" :disabled="item.disabled"
                        :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="人工判断">
                <el-switch v-model="formModel.is_judge" />
            </el-form-item>
            <el-form-item label="标记结束">
                <el-switch v-model="formModel.is_end" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="onCancel">取消</el-button>
                <el-button type="primary" @click="onSubmit">保存</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup name="DrawerModifyEvent">
/**
 * 这里触发的事件，统一从 @/../workflow.event.js 的 useInject 函数中中引入
 */
import { nextTick, reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useInject } from "@/utils/workflow/workflow.event.js"
import { enumEventModule, enumEventName } from "@/utils/emunEvent.js"
import { fetchLinkageModules } from "@/api/linkage.services"
// import {WorkflowApi} from "@/api/workflow.js";


const {
    getWorkflowCls,
    appendEvent,
    modifyEvent
} = useInject()

const refForm = ref(null)
const visible = ref(false)
const loading = ref(false)
const isCreate = ref(true)
const currentModule = ref(enumEventModule.event)
const useToEnd = ref(false)
const toEndAction = ref(false)

let currentType
// let cacheNodeData
// let cacheExtraData

// const isJudgment = computed(() => {
//     return currentModule.value.startsWith('judgment')
// })

let nodeID

const formModel = ref({
    module_id: null,
    is_judge: false,
    is_end: false
})

const assignData = reactive({
    from: [],
    to: []
})

const rules = {
    module_id: { required: true, message: '请选择调用模块', trigger: 'change' }
}
const onCancel = () => {
    visible.value = false
    loading.value = false
    // formModel.value = {}
}

const onSubmit = async () => {
    if (!refForm.value) {
        return
    }
    const valid = await refForm.value.validate()
    if (!valid) {
        return
    }

    const row = modules.value.find(item => item.id == formModel.value.module_id)
    formModel.value.name = row.name

    //禁用已经选择的模块
    //modules.value = formatTreeData(result.data)


    if (isCreate.value) {
        const edgeConfig = {}
        getWorkflowCls(cls => {
            switch (currentModule.value) {
                case enumEventModule.judgmentValid:
                    edgeConfig.from = {
                        shape: 'edge',
                        ...cls.edgeValidAttrs
                    }
                    break
                case enumEventModule.judgmentInvalid:
                    edgeConfig.from = {
                        shape: 'edge',
                        ...cls.edgeInvalidAttrs
                    }
                    break
                default:
                    break
            }
        })
        appendEvent({
            data: {
                module: currentModule.value,
                ...formModel.value
            },
            from: assignData.from,
            to: assignData.to,
            edgeConfig,
            toEnd: toEndAction.value
        })

        if (currentType == enumEventName.appendChild) {
            getWorkflowCls(cls => {
                cls.removeEdges(assignData.from, assignData.to)
            })
        }
    } else {
        modifyEvent({
            id: nodeID,
            data: {
                module: currentModule.value,
                ...formModel.value
            },
            toEnd: toEndAction.value
        })
    }

    ElMessage.success(isCreate.value ? '创建成功' : '更新成功')

    onCancel()

}

/**
 * 展开 Drawer
 * @param {enumEventName}       param.type 触发类型
 * @param {TNodeID}             param.id 需要编辑的 node id
 * @param {Any}                 param.data 当前模块的数据
 * @param {enumEventModule}     param.data.module 当前模块的数据
 * @param {Any}     param.data.organization_code 选中的部门 id
 * @param {String}     param.data.content 选中的部门名称
 * @param {String}     param.data.description 备注
 * @param {Array[Any]}     param.data.actions 额外的操作事件
 * @param {Any}                 param.extra 额外需要再提交时使用的数据
 * @param {TNodeID | TNodeID[]} param.from 需要关联的起点节点 id 集合
 * @param {TNodeID | TNodeID[]} param.to 需要关联的终点节点 id 集合
 */
const open = ({ type, id, data = {}, extra = {}, from = [], to = [] }) => {
    currentType = type
    currentModule.value = data.module ?? enumEventModule.event
    isCreate.value = id === void 0
    nodeID = id
    assignData.from = Array.isArray(from) ? from : [from]
    assignData.to = Array.isArray(to) ? to : [to]

    if (assignData.from[0] !== void 0) {
        getWorkflowCls(cls => {
            const fromNode = cls.getExtraNode(assignData.from[0])
            useToEnd.value = !fromNode.to?.length
        })
    }

    visible.value = true

    nextTick(() => {
        refForm.value.resetFields()

        formModel.value = {
            module_id: null,
            is_judge: false,
            is_end: false,
            name: ''
        }
    })
}

const modules = ref([])
const loadLinkageModules = async () => {
    try {
        const result = await fetchLinkageModules()
        if (result.code == 1) {
            modules.value = formatTreeData(result.data)
        }
    } catch (xhr) {
        modules.value = []
    }
}
const formatTreeData = (data) => {
    // const loop = (item) => {
    //     item.disabled = !!item.disabled

    //     if (Array.isArray(item.children) && item.children.length) {
    //         item.children = item.children.map(child => loop(child))
    //     }

    //     return item
    // }

    // const list = data?.map(item => {
    //     return loop(item)
    // }) || []
    const list = data?.map((item, index) => {
        return {
            id: item.id,
            name: item.name,
            disabled: false
        }
    }) || []
    return list
}

onMounted(() => {
    loadLinkageModules()
})

defineExpose({
    open
})

</script>

<style lang="scss" module>
.modify-drawer {
    @include defineEl('drawer__header') {
        margin-bottom: 0;
    }

    @include defineEl('drawer__body') {
        --el-drawer-padding-primary: 20px 20px 10px;
    }
}

.modify-wrapper {
    & [class~='el-select'] {
        width: 80%;
    }
}

.table-wrapper {
    flex: 1;
    height: 0;
}

.button-wrapper {
    display: flex;
    justify-content: right;
    align-items: center;
    padding-top: 10px;
}
</style>